package com.wosai.teach.thread;

import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;

import com.wosai.teach.utils.FixedSpeedScroller;

public class LunBoRunnable implements Runnable {
	// 无线循环 http://blog.csdn.net/gaojinshan/article/details/18038181

	/**
	 * 控制切换速度
	 */
	private FixedSpeedScroller scroller;

	private ViewPager viewPager;

	private Handler handler;

	private int size;

	private boolean stopFlag = false;

	public LunBoRunnable(ViewPager viewPager, int size, Handler handler) {
		this.viewPager = viewPager;
		this.handler = handler;
		this.size = size;
	}

	public void run() {
		if (stopFlag) {
			return;
		}
		int count = viewPager.getAdapter().getCount();
		if (count > 1) { // 多于1个，才循环
			int index = viewPager.getCurrentItem();
			index = (index + 1) % count;
			viewPager.setCurrentItem(index, true);
			if (scroller != null) {
				scroller.setmDuration(1 * 1000);
			}
		}
		handler.postDelayed(this, 4000);
	}

	public void run2() {
		if (stopFlag) {
			return;
		}
		int item = viewPager.getCurrentItem();
		item++;
		if (item >= size) {
			item = 0;
		}

		viewPager.setCurrentItem(item);
		handler.postDelayed(this, 4000);
	}

	public void run3() {
		if (stopFlag) {
			return;
		}
		while (true) {
			SystemClock.sleep(4 * 1000);
			int item = viewPager.getCurrentItem();
			item++;
			if (item >= size) {
				item = 0;
			}
			viewPager.setCurrentItem(item);
		}
	}

	public void setStopFlag(boolean stopFlag) {
		this.stopFlag = stopFlag;
	}

	public void setScroller(FixedSpeedScroller scroller) {
		this.scroller = scroller;
	}
}
